<template>
	<div>
		<pageViewContainer :show-header="showMainHeader">
			<template #left>
				<SearchCard style="width: 290px;" v-show="showSearchArea" ref="searchCard" class="search-card"
					:formOption="searchFormOption" @searchSubmit="handleSearchSubmit" @resetSubmit="handleSearchReset"
					:show-header="false" :show-reset-button="true" :show-submit-button="true" submit-button-text="搜索"
					reset-button-text="重置" />
			</template>
			<el-card shadow="never">
				<template #header>
					<div class="card-header"
						style="display: flex; justify-content: space-between; align-items: center;">
						<div style="display: flex; align-items: center; gap: 15px;">
							<span>附件列表</span>
							<!-- 全选功能区域 -->
							<div style="display: flex; align-items: center; gap: 10px;" v-if="!isPickerMode">
								<el-checkbox v-model="selectAll" :indeterminate="isIndeterminate"
									@change="handleSelectAllChange" size="small">
									全选
								</el-checkbox>
								<span v-if="selectedCount > 0" style="color: #409EFF; font-size: 14px;">
									已选择 {{ selectedCount }} 项
								</span>
								<el-button v-if="selectedCount > 0" type="text" size="small"
									@click="handleClearSelection" style="color: #909399;">
									取消选择
								</el-button>
							</div>
						</div>
						<div>
							<el-button size="small" type="success" icon="Upload" @click="uploadClick"
								style="margin-right: 10px;">上传</el-button>
							<el-button-group>
								<el-button size="small" type="primary" icon="Search"
									@click="showSearchArea = !showSearchArea">搜索</el-button>
								<el-button size="small" type="primary" icon="Delete" @click="deleteClick">删除</el-button>
							</el-button-group>
						</div>
					</div>
				</template>
				<div style="padding: 10px;" v-loading="loading" element-loading-text="加载中...">
					<attachmentListTem ref="attachmentListRef" :list="list" @refresh="getList"
						:isPickerMode="isPickerMode" :pickerMultiple="pickerMultiple"
						@picker-selection-change="handlePickerSelectionChange"
						@selection-change="handleSelectionChange">
					</attachmentListTem>
				</div>
				<template #footer>
					<el-pagination @current-change="handleCurrentPageChange" @size-change="handleSizeChange"
						size="small" background layout="total, sizes, prev, pager, next, jumper" :total="total"
						:page-size="limit" :current-page="page" :page-sizes="[10, 20, 30, 50, 100]"
						style="justify-content: flex-end;" />
				</template>

			</el-card>
			<template #headerTool>
				<el-button type="primary" icon="Setting" @click="openFilesystemConfig">存储配置</el-button>
			</template>
			<template #right>
				<div class="detailTem">
					<detailTem ref="detailTem"></detailTem>
				</div>
			</template>
			<uploadViewTem ref="uploadViewTem" @refresh="getList"></uploadViewTem>

			<!-- 文件系统配置抽屉 -->
			<el-drawer v-model="filesystemConfigVisible" title="存储配置管理" size="60%">
				<filesystemConfig ref="filesystemConfigRef" />
			</el-drawer>
		</pageViewContainer>
	</div>
</template>

<script>
import {
	useAttachmentStore
} from "../../../stores/attachment"
import uploadViewTem from './components/uploadView.vue'
import detailTem from "./components/detail.vue"
import attachmentListTem from "./components/attachmentList.vue"
import filesystemConfig from "./components/filesystemConfig.vue"
import SearchCard from '../../../components/common/searchCard.vue';
import { ElMessage } from 'element-plus'

export default {
	components: {
		detailTem,
		attachmentListTem,
		uploadViewTem,
		filesystemConfig,
		SearchCard
	},
	props: {
		showMainHeader: {
			type: Boolean,
			default: true,
		},
		isPickerMode: {
			type: Boolean,
			default: false,
		},
		pickerMultiple: {
			type: Boolean,
			default: false,
		},
	},
	data() {
		return {
			list: [],
			page: 1,
			limit: 30,
			total: 0,
			selectedItemsForPicker: [],
			showSearchArea: true,
			searchCriteria: {},
			loading: false,
			filesystemConfigVisible: false,
			searchFormOption: [
				{
					label: 'ID',
					key: 'id',
					componentsName: 'el-input',
					value: '',
					props: {
						type: 'number',
						placeholder: '精确搜索ID',
						clearable: true
					}
				},
				{
					label: '文件名',
					key: 'name',
					componentsName: 'el-input',
					value: '',
					props: {
						placeholder: '模糊搜索文件名',
						clearable: true
					}
				},
				{
					label: '文件类型',
					key: 'type',
					componentsName: 'el-select',
					value: '',
					props: {
						placeholder: '选择文件类型',
						clearable: true
					},
					options: [] // 动态填充
				},
				{
					label: '存储磁盘',
					key: 'disk',
					componentsName: 'el-input',
					value: '',
					props: {
						placeholder: '例如 local, aliyun',
						clearable: true
					}
				},
				{
					label: '存储路径',
					key: 'path',
					componentsName: 'el-input',
					value: '',
					props: {
						placeholder: '模糊搜索路径',
						clearable: true
					}
				},
				{
					label: '文件URL',
					key: 'url',
					componentsName: 'el-input',
					value: '',
					props: {
						placeholder: '模糊搜索URL',
						clearable: true
					}
				},
				{
					label: '上传者类型',
					key: 'uploader_type',
					componentsName: 'el-select',
					value: 'admin',
					props: {
						placeholder: '选择上传者类型',
						clearable: true
					},
					options: [
						{
							label: '管理员（admin）',
							value: 'admin'
						},
						{
							label: '客户端（client）',
							value: 'client'
						}
					]
				},
				{
					label: '上传时间',
					key: 'add_time_range',
					componentsName: 'el-date-picker',
					value: [],
					props: {
						type: 'datetimerange',
						placeholder: '选择上传日期时间范围',
						'value-format': 'YYYY-MM-DD HH:mm:ss'
					}
				}
			],
			selectAll: false,
			isIndeterminate: false,
			selectedCount: 0
		}
	},
	computed: {
		attachmentStore() {
			return useAttachmentStore()
		},
		hasSelectedAttachment() {
			const info = this.attachmentStore.currentFileInfo.info;
			return info && Object.keys(info).length > 0 && info.id !== undefined;
		}
	},
	async created() {
		// 从搜索表单配置中提取默认值
		this.initializeDefaultSearchCriteria()
		this.getList()
		this.selectedItemsForPicker = [];

		// 获取上传配置信息
		try {
			await this.attachmentStore.getUploadConfig();
			// 更新搜索表单选项
			this.updateSearchFormOptions();
		} catch (error) {
			ElMessage.error('获取上传配置失败，' + error.message);
		}
	},
	watch: {
		pickerMultiple() {
			this.selectedItemsForPicker = [];
			if (this.$refs.attachmentListRef && typeof this.$refs.attachmentListRef.clearSelection === 'function') {
				this.$refs.attachmentListRef.clearSelection();
			}
		}
	},
	methods: {
		handleCurrentPageChange(newPage) {
			this.page = newPage;
			this.getList();
		},
		handleSizeChange(newSize) {
			this.limit = newSize;
			this.page = 1;
			this.resetSelectionState();
			this.getList();
		},
		getList() {
			this.loading = true;
			let where = { ...this.searchCriteria };
			this.attachmentStore.getList(where, this.page, this.limit).then(res => {
				if (res.code !== 200) {
					throw new Error(res.message)
				}
				this.list = res.data.list
				this.total = res.data.count
				// 重置选择状态
				this.resetSelectionState();
			}).catch(err => {
				ElMessage.error(err.message || '获取附件列表失败')
				console.error("Error fetching attachments:", err)
				this.list = []
				this.total = 0
				this.resetSelectionState();
			}).finally(() => {
				this.loading = false;
			})
		},
		handleSearchSubmit(searchData) {
			// 文件类型字段不需要特殊处理，直接使用type字段
			// 如果文件类型为空字符串，删除该字段
			if (searchData.type === '') {
				delete searchData.type;
			}

			this.searchCriteria = searchData;
			this.page = 1;
			this.getList();
		},
		handleSearchReset() {
			this.searchCriteria = {};
			this.page = 1;
			this.$refs.searchCard.resetFormFields();
			this.getList();
		},
		uploadClick() {
			this.$refs.uploadViewTem.open()
		},
		deleteClick() {
			const idsToDelete = this.$refs.attachmentListRef ? this.$refs.attachmentListRef.checkboxList : [];

			if (idsToDelete.length === 0) {
				return ElMessage.warning("请选择要删除的附件")
			}

			this.$confirm(`确定删除选中的 ${idsToDelete.length} 个附件吗?`, '提示', {
				type: 'warning'
			}).then(() => {
				this.attachmentStore.del(idsToDelete).then(() => {
					ElMessage.success("删除成功")
					this.getList()
					this.selectedItemsForPicker = this.selectedItemsForPicker.filter(item => !idsToDelete.includes(item.id));
					if (this.$refs.attachmentListRef && typeof this.$refs.attachmentListRef.clearSelectionAfterDelete === 'function') {
						this.$refs.attachmentListRef.clearSelectionAfterDelete(idsToDelete);
					} else if (this.$refs.attachmentListRef && typeof this.$refs.attachmentListRef.clearSelection === 'function') {
						this.$refs.attachmentListRef.clearSelection();
					}
				}).catch(err => {
					ElMessage.error(err.message || '删除失败');
					console.error("Error deleting attachments:", err);
				});
			}).catch(() => {
				// User cancelled the confirm dialog
			});
		},
		handlePickerSelectionChange(selection) {
			this.selectedItemsForPicker = selection;
		},
		getSelectedItems() {
			return this.selectedItemsForPicker;
		},
		initializeDefaultSearchCriteria() {
			// 从搜索表单配置中提取有默认值的字段
			const defaultCriteria = {};
			this.searchFormOption.forEach(option => {
				// 只有当默认值不为空且不是空数组时才添加到搜索条件中
				if (option.value !== undefined && option.value !== '' && option.value !== null) {
					// 对于数组类型（如日期范围），检查是否为非空数组
					if (Array.isArray(option.value)) {
						if (option.value.length > 0) {
							defaultCriteria[option.key] = option.value;
						}
					} else {
						defaultCriteria[option.key] = option.value;
					}
				}
			});

			// 将默认搜索条件设置到searchCriteria中
			this.searchCriteria = { ...defaultCriteria };

			console.log('初始化默认搜索条件:', this.searchCriteria);
		},
		handleSelectAllChange(value) {
			this.selectAll = value;
			this.isIndeterminate = false;
			this.selectedCount = value ? this.list.length : 0;
			if (this.$refs.attachmentListRef && typeof this.$refs.attachmentListRef.selectAll === 'function') {
				this.$refs.attachmentListRef.selectAll(value);
			}
		},
		handleClearSelection() {
			this.selectAll = false;
			this.isIndeterminate = false;
			this.selectedCount = 0;
			if (this.$refs.attachmentListRef && typeof this.$refs.attachmentListRef.clearSelection === 'function') {
				this.$refs.attachmentListRef.clearSelection();
			}
		},
		handleSelectionChange(selection) {
			this.selectedCount = selection.length;

			// 更新全选状态
			if (selection.length === 0) {
				this.selectAll = false;
				this.isIndeterminate = false;
			} else if (selection.length === this.list.length) {
				this.selectAll = true;
				this.isIndeterminate = false;
			} else {
				this.selectAll = false;
				this.isIndeterminate = true;
			}
		},
		resetSelectionState() {
			this.selectAll = false;
			this.isIndeterminate = false;
			this.selectedCount = 0;
		},
		updateSearchFormOptions() {
			if (!this.attachmentStore.uploadConfig?.allowedFileTypes) {
				return;
			}

			const allowedFileTypes = this.attachmentStore.uploadConfig.allowedFileTypes;

			// 更新文件类型选项
			const fileTypeIndex = this.searchFormOption.findIndex(item =>
				item.key === 'type'
			);
			if (fileTypeIndex !== -1) {
				this.searchFormOption[fileTypeIndex].options = Object.keys(allowedFileTypes).map(key => ({
					label: allowedFileTypes[key].name,
					value: key
				}));
			}
		},
		openFilesystemConfig() {
			this.filesystemConfigVisible = true;
		}
	}
}
</script>

<style lang="less" scoped>
.left-search-panel {
	width: 300px;
	margin-right: 15px;
	background-color: #ffffff;
	border-radius: 4px;
	padding: 15px;
	box-sizing: border-box;
}

.slide-fade-left-enter-active {
	transition: all .3s ease-out;
}

.slide-fade-left-leave-active {
	transition: all .3s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}

.slide-fade-left-enter-from,
.slide-fade-left-leave-to {
	transform: translateX(-20px);
	opacity: 0;
}

.el-card {
	:deep(.el-card__header) {
		background-color: #ffffff;

	}

	:deep(.el-card__body) {
		padding: 0px;
	}

	:deep(.el-card__footer) {
		background-color: #ffffff;
		padding: 10px 20px;
	}
}

.search-card {
	:deep(.el-card__header) {
		background-color: #ffffff;

	}
}

.detailTem {
	height: 100%;
	width: 300px;

}
</style>